package vip.liux.contracts.infrastructure.messaging.interceptors;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;

public class LoggingChannelInterceptor implements ChannelInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LoggingChannelInterceptor.class);

    @Override
    public void afterSendCompletion(@NotNull Message<?> message, @NotNull MessageChannel channel, boolean sent, Exception ex) {
        if (ex != null) {
            log.error("消息发送异常: {}, 异常: {}", message, ex.getMessage(), ex);
        } else {
            log.info("消息发送完成且无异常: {}", message);
        }
    }

    @Override
    public void postSend(@NotNull Message<?> message, @NotNull MessageChannel channel, boolean sent) {

        log.info("消息发送完成: {}", message);
    }

    @Override
    public Message<?> preSend(@NotNull Message<?> message, @NotNull MessageChannel channel) {
        log.info("消息发送前: {}", message);
        return ChannelInterceptor.super.preSend(message, channel);
    }
}
